package net.jueb.frameworkDemo.orm.mongodb.driver;

import org.bson.BsonReader;
import org.bson.BsonWriter;
import org.bson.codecs.Codec;
import org.bson.codecs.DecoderContext;
import org.bson.codecs.EncoderContext;

public class EnumCodec<E extends Enum<E>> implements Codec<E>{
	  
	private Class<E> type;

	public EnumCodec(Class<E> type) {
	   if (type == null) {
	     throw new IllegalArgumentException("Type argument cannot be null");
	   }
	   this.type = type;
	 }
	
	@Override
	public void encode(BsonWriter writer, E value, EncoderContext encoderContext) {
		writer.writeString(value.name());
	}

	@Override
	public Class<E> getEncoderClass() {
		return type;
	}

	@Override
	public E decode(BsonReader reader, DecoderContext decoderContext) {
		String name=reader.readString();
		return Enum.valueOf(type, name);
	}
}
